package com.pdstudio.weather;

import java.util.ArrayList;
import java.util.List;

import com.pdstudio.app.Application;
import com.pdstudio.app.Application.EventHandler;
import com.pdstudio.bean.County;
import com.pdstudio.bean.MyStationState;
import com.pdstudio.bean.NewStationState;
import com.pdstudio.http.StationHttpMethod;
import com.pdstudio.plistview.NewStationStateListView;
import com.pdstudio.util.DateTimePickDialogUtil;
import com.pdstudio.util.SharePreferenceUtil;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class NewStationListStateActivity extends Activity implements
		EventHandler {

	private NewStationStateListView mNewStationStateListView;
	private List<MyStationState> mMyStationStates;
	private View customLiveIndexTitleView;
	private TextView txtTitle;
	private ImageView ivBack;
	private SharePreferenceUtil mSpUtil;
	private Application mApplication;

	private EditText startDateTime;
	private EditText endDateTime;

	private String initStartDateTime; // 初始化开始时间
	private String initEndDateTime; // 初始化结束时间

	private Spinner mSpinner;
	// 区县下拉列表适配器
	private ArrayAdapter<String> mCountyArrayAdapter;

	// 所有县市
	private List<County> mCounties;

	private static final int MESSAGE_GETALLCOUNTIES = 0;
	private static final int MESSAGE_GETALLSTATES = 1;

	private Handler handler = null;

	// 查询条件区县
	private String mConditionCounty = "";

	private List<NewStationState> mStationStates;

	private ImageButton mBtnSearch;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_new_station_list_state);

		handler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case MESSAGE_GETALLCOUNTIES:
					mCounties = (List<County>) msg.obj;
					setSpinner();
					break;
				case MESSAGE_GETALLSTATES:
					mStationStates = (List<NewStationState>) msg.obj;
					if (mStationStates.size() == 0) {
						Toast.makeText(getApplicationContext(), "当前没有数据",
								Toast.LENGTH_SHORT).show();
					} else {
						mMyStationStates = convertStationStateToMyStationState(mStationStates);
						setStateList();
					}
					break;
				}
			}

		};

		Application.mListeners.add(this);
		mApplication = Application.getInstance();
		mSpUtil = mApplication.getSharePreferenceUtil();

		mConditionCounty = "";

		LinearLayout layout = (LinearLayout) findViewById(R.id.activity_new_station_list_state);
		int resId = mApplication.getApplicationBackground(mSpUtil
				.getWeatherStatus());
		layout.setBackground(getResources().getDrawable(resId));

		customLiveIndexTitleView = findViewById(R.id.title_stationlist);
		txtTitle = (TextView) customLiveIndexTitleView
				.findViewById(R.id.title2_text_nav);
		txtTitle.setText("站点实况");

		ivBack = (ImageView) customLiveIndexTitleView
				.findViewById(R.id.title2_back);
		ivBack.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				NewStationListStateActivity.this.finish();
			}
		});

		// 两个输入框
		startDateTime = (EditText) findViewById(R.id.startDate);
		endDateTime = (EditText) findViewById(R.id.endDate);

		getStartTime();
		getEndTime();

		startDateTime.setText(initStartDateTime);
		endDateTime.setText(initEndDateTime);

		startDateTime.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {

				DateTimePickDialogUtil dateTimePicKDialog = new DateTimePickDialogUtil(
						NewStationListStateActivity.this, initStartDateTime);
				dateTimePicKDialog.dateTimePicKDialog(startDateTime);

			}
		});

		endDateTime.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				DateTimePickDialogUtil dateTimePicKDialog = new DateTimePickDialogUtil(
						NewStationListStateActivity.this, initEndDateTime);
				dateTimePicKDialog.dateTimePicKDialog(endDateTime);
			}
		});

		mSpinner = (Spinner) findViewById(R.id.station_state_city_spinner);

		initData();
		initStates();

		mBtnSearch = (ImageButton) findViewById(R.id.search_state_list);
		mBtnSearch.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				searchData();
			}

		});

	}

	/**
	 * 列表绑定数据
	 * */
	private void setStateList() {
		mNewStationStateListView = (NewStationStateListView) findViewById(R.id.station_state_list);
		mNewStationStateListView.updateData(mMyStationStates);
	}

	/**
	 * 初始化所有站点状况
	 * */
	private void initStates() {
		Thread thread = new Thread() {
			@Override
			public void run() {
				try {
					StationHttpMethod http = new StationHttpMethod(
							NewStationListStateActivity.this);
					mStationStates = http.GetNewStationStates(mSpUtil
							.getAuthCode(), mConditionCounty, startDateTime
							.getText().toString(), endDateTime.getText()
							.toString());
					Message msg = handler.obtainMessage(MESSAGE_GETALLSTATES,
							mStationStates);
					handler.sendMessage(msg);
				} catch (Exception ex) {
				}
			}
		};
		thread.start();

	}

	private void getStartTime() {
		initStartDateTime = DateTimePickDialogUtil.getYesterdayStringDate();
	}

	private void getEndTime() {
		initEndDateTime = DateTimePickDialogUtil.getStringDate();
	}

	private void setSpinner() {
		mCountyArrayAdapter = new ArrayAdapter<String>(getApplicationContext(),
				R.layout.new_simple_spinner_item,
				convertCountyListToStringList(mCounties));
		// 设置下拉列表的风格
		mCountyArrayAdapter
				.setDropDownViewResource(R.layout.new_simple_spinner_dropdown_item);

		mSpinner.setAdapter(mCountyArrayAdapter);
		mSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO 设置查询条件
				mConditionCounty = mCounties.get(position).getCounty();

			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				//

			}
		});
	}

	/**
	 * 初始化下拉框
	 * */
	private void initData() {

		Thread thread = new Thread() {
			@Override
			public void run() {
				try {
					StationHttpMethod http = new StationHttpMethod(
							NewStationListStateActivity.this);
					mCounties = http.GetAllCounties(mSpUtil.getAuthCode());
					Message msg = handler.obtainMessage(MESSAGE_GETALLCOUNTIES,
							mCounties);
					handler.sendMessage(msg);
				} catch (Exception ex) {

				}
			}
		};
		thread.start();

	}

	/**
	 * County对象转为String
	 * */
	private List<String> convertCountyListToStringList(List<County> counties) {

		List<String> newCounties = new ArrayList<String>();

		for (int i = 0; i < counties.size(); i++) {
			String county = counties.get(i).getCounty();
			newCounties.add(county);
		}

		return newCounties;
	}

	private List<MyStationState> convertStationStateToMyStationState(
			List<NewStationState> stationStates) {

		List<MyStationState> result = new ArrayList<MyStationState>();

		// 先取出所有地名存放在StringBuffer中

		StringBuffer addes = new StringBuffer();

		String address = "";
		for (int i = 0; i < stationStates.size(); i++) {
			if (i == 0) {
				address = stationStates.get(i).county;
				addes.append(address + ";");
			} else {
				if (!stationStates.get(i).county.equals(address)) {
					address = stationStates.get(i).county;
					addes.append(address + ";");
				}
			}
		}
		if (addes.toString().contains(";")) {
			addes.replace(addes.length() - 1, addes.length() - 1, "");
		}

		String[] adds = addes.toString().split(";");

		for (int i = 0; i < adds.length; i++) {
			MyStationState myStationState = new MyStationState();
			myStationState.setAddress(adds[i]);

			List<NewStationState> newStates = new ArrayList<NewStationState>();
			for (int j = 0; j < stationStates.size(); j++) {
				if (stationStates.get(j).county.equals(adds[i])) {
					NewStationState s = new NewStationState();
					s = stationStates.get(j);
					newStates.add(s);
				}
			}
			myStationState.setStationStateList(newStates);

			result.add(myStationState);
		}

		return result;
	}

	private void searchData() {
		initStates();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.new_station_list_state, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onCityComplite() {

	}

	@Override
	public void onNetChange() {

	}
}
